package com.itheima.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AdminMapper;
import com.itheima.dao.CategoryMenuMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Admin;
import com.itheima.pojo.CategoryMenu;
import com.itheima.pojo.File;
import com.itheima.pojo.Role;
import com.itheima.service.AdminService;
import com.itheima.service.FileService;
import com.itheima.utils.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private CategoryMenuMapper categoryMenuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate ;

    @Autowired
    private FileService fileService;


    @Override
    public Admin findByusername(String userName) {
        Admin admin1 = new Admin();
        Admin admin2 = new Admin();
        Admin admin3 = new Admin();
        admin1.setUserName(userName);
        admin2.setMobile(userName);
        admin3.setEmail(userName);
        Admin adminInfo = adminMapper.selectOne(admin1);
        if (adminInfo != null) {
            adminInfo.setLastLoginTime(new Date());
            return adminInfo;
        }
        adminInfo = adminMapper.selectOne(admin2);
        if (adminInfo != null) {
            return adminInfo;
        }
        adminInfo = adminMapper.selectOne(admin3);
        if (adminInfo != null) {
            return adminInfo;
        }

        throw new RuntimeException();
    }

    /**
     * 根据登录用户获取相应菜单选项
     *
     * @param userName
     * @return
     */
    @Override
    public Map<String, Object> getMenu(String userName) {
        Admin admin = findByusername(userName);
        Role role = roleMapper.selectByPrimaryKey(admin.getRoleUid());
        String categoryMenuUids = role.getCategoryMenuUids();
        List<String> menuUids = JSONArray.parseArray(categoryMenuUids, String.class);
        List<CategoryMenu> sonList = new ArrayList<>();
        List<CategoryMenu> parentList = new ArrayList<>();
        List<CategoryMenu> buttonList = new ArrayList<>();
        for (String menuUid : menuUids) {
            CategoryMenu categoryMenu = categoryMenuMapper.selectByPrimaryKey(menuUid);
            if (categoryMenu != null) {
                if (categoryMenu.getMenuLevel() == 2) {
                    sonList.add(categoryMenu);
                }
                //获取父类菜单项
                if (categoryMenu.getMenuLevel() == 1) {
                    parentList.add(categoryMenu);
                }
                //获取按钮菜单
                if (categoryMenu.getMenuLevel() == 3) {
                    buttonList.add(categoryMenu);
                }
            }
        }
        parentList.sort(new Comparator<CategoryMenu>() {
            @Override
            public int compare(CategoryMenu o1, CategoryMenu o2) {
                return o1.getSort()<o2.getSort()?1:-1;
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("sonList", sonList);
        map.put("buttonList", buttonList);
        map.put("parentList", parentList);
        return map;
    }

    @Override
    public void add(Admin admin) {
        String s = adminMapper.selectByName(admin.getUserName());
        if (s != null) {
            throw new RuntimeException("用户名重复");
        }
        admin.setUid(idWorker.nextId().toString());
        admin.setCreateTime(new Date());
        admin.setUpdateTime(new Date());
        String encode = passwordEncoder.encode("123456");
        admin.setPassWord(encode);
        int i = adminMapper.insertSelective(admin);
        if (i <= 0) {
            throw new RuntimeException("添加失败");
        }
    }

    @Override
    public void update(Admin admin) {
        admin.setUpdateTime(new Date());
        int i = adminMapper.updateByPrimaryKeySelective(admin);
        if (i <= 0) {
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public Map<String, Object> assign(String adminUid) {
        if (adminUid == null) {
            throw new RuntimeException("管理员id错误");
        }
        Admin adminInfo = adminMapper.selectByPrimaryKey(adminUid);
        List<Role> roles = roleMapper.selectAll();
        Role role = roleMapper.selectByPrimaryKey(adminInfo.getRoleUid());
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> admin = new HashMap<>();
        admin.put("userName", adminInfo.getUserName());
        admin.put("roleUid", adminInfo.getRoleUid());
        admin.put("passWord", adminInfo.getPassWord());
        admin.put("nickName", adminInfo.getNickName());
        admin.put("gender", adminInfo.getGender());
        admin.put("avatar", adminInfo.getAvatar());
        admin.put("email", adminInfo.getEmail());
        admin.put("loginCount", adminInfo.getLoginCount());
        admin.put("lastLoginTime", adminInfo.getLastLoginTime());
        admin.put("lastLoginIp", adminInfo.getLastLoginIp());
        admin.put("uid", adminInfo.getUid());
        admin.put("status", adminInfo.getStatus());
        admin.put("createTime", adminInfo.getCreateTime());
        admin.put("updateTime", adminInfo.getUpdateTime());
        map.put("unassignRoles", roles);
        map.put("assignedRoles", role);
        map.put("admin", admin);
        return map;
    }

    @Override
    public void delete(String adminUid) {
        try {
            adminMapper.deleteByPrimaryKey(adminUid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("操作失败");
        }
    }

    @Override
    public void forceLogout(List<String> tokenList) {

    }

    @Override
    public Map<String, Object> getList(String keyword, Long currentPage, Long pageSize, HttpServletRequest request) {
        try {
            Map<String,Object> map =new HashMap<>();
            List<Admin> records =new ArrayList<>();
            PageHelper.startPage(currentPage.intValue(),pageSize.intValue());
            Example example = createExample(keyword);
            Page<Admin> page = (Page<Admin>) adminMapper.selectByExample(example);
            for (Admin admin : page.getResult()) {
                //获取头像路径
                String path = "http://qf01xhkh2.hn-bkt.clouddn.com/";
                List<String> photoList = new ArrayList<>();
                String avatar = admin.getAvatar();
                String[] strings = avatar.split(",");
                for (String string : strings) {
                    if (StringUtils.isNotEmpty(string)){
                        avatar = string;
                        File file = fileService.findFileById(avatar);
                        String picUrl = file.getPicUrl();
                        if (!picUrl.startsWith("/")){
                            picUrl="/"+picUrl;
                        }
                        path=path+picUrl;
                        photoList.add(path);
                    }
                }
                String roleUid = admin.getRoleUid();
                admin.setRole(roleMapper.selectByPrimaryKey(roleUid));
                admin.setPhotoList(photoList);
                records.add(admin);
            }
            map.put("records",records);
            map.put("total",page.getTotal());
            map.put("size",page.getPageSize());
            map.put("current",page.getPageNum());
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("操作失败");
        }
    }

    @Override
    public Admin findByUid(String adminUid) {
        Admin admin = adminMapper.selectByPrimaryKey(adminUid);
        if (admin==null){
            throw  new RuntimeException();
        }
        return admin;
    }


    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(String keyword){
        Example example=new Example(Admin.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(keyword)) {
            criteria.orLike("userName", "%"+keyword+"%").orLike("summary","%"+keyword+"%").orLike("nickName","%"+keyword+"%");
        }
        return example;
    }
}
